package top.haichi.webpaper.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.haichi.webpaper.entity.Result;
import top.haichi.webpaper.entity.Student;
import top.haichi.webpaper.entity.Teacher;
import top.haichi.webpaper.entity.User;
import top.haichi.webpaper.mapper.MessageMapper;
import top.haichi.webpaper.mapper.StudentMapper;
import top.haichi.webpaper.mapper.TeacherMapper;
import top.haichi.webpaper.mapper.UserMapper;
import top.haichi.webpaper.service.UserLoginService;
import top.haichi.webpaper.utils.JwtUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@Slf4j
@Service

public class UserLoginServiceImpl implements UserLoginService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private TeacherMapper teacherMapper;
    @Autowired
    private MessageMapper messageMapper;


    /**
     * 登录服务
     *
     * @param user
     * @return
     */
    @Override
    public Result login(User user) {
        log.info(user + "登陆了");
        if (user == null || user.getUsername() == null || user.getPassword() == null) {
            return Result.error("请输入用户名和密码");
        }
        User loginUser = userMapper.getByUsernameAndPassword(user);
        //登陆失败
        if (loginUser == null) {
            return Result.error("用户名或密码错误");
        }
        HashMap<String, Object> claims = new HashMap<>();
        //从数据库中查询到的用户信息
        User loggedUser = userMapper.getUserWithoutPassword(user);
        claims.put("status", loggedUser.getStatus());
        claims.put("id", loggedUser.getId());
        String token = JwtUtils.generateJwt(claims);
        HashMap<String, Object> resultMap = new HashMap<>();
        resultMap.put("user", loggedUser);
        resultMap.put("token", token);
        HashMap<String, Object> selectMap = new HashMap<>();
        selectMap.put("target",loggedUser.getId());
        selectMap.put("is_new",true);
        boolean hasNew = !messageMapper.selectByMap(selectMap).isEmpty();
        resultMap.put("hasNew",hasNew);
        //登录校验为学生
        if (loginUser.getStatus().equals("student")) {
            Student loginStudent = userMapper.getStudentByUsername(user);
            if (studentMapper.getIdById(loginStudent) == null) {
                return Result.success("请及时完善用户信息，否则会影响使用", resultMap);
            } else {
                Result result = Result.success("登陆成功", resultMap);
                return result;
            }
        }
        //登录校验为老师
        else if (loginUser.getStatus().equals("teacher")) {
//            Teacher loginTeacher = userMapper.getTeacherByUsername(user);
//            if (teacherMapper.getIdById(loginTeacher) == null) {
//                return Result.success("请及时完善用户信息，否则会影响使用", resultMap);
//            } else {
                Result result = Result.success("登陆成功", resultMap);
                return result;
        }else if(loginUser.getStatus().equals("admin")){
            Result result = Result.success("登陆成功", resultMap);
            return result;
        }
//        }
        log.warn("未定义的身份" + loggedUser);
        return Result.error("操作异常，请联系管理员");
    }


    /**
     * 注册服务
     *
     * @param user
     * @return
     */
    @Override
    public Result register(User user) {
        log.info(user + "注册了");
        //输入有效性验证
        if (user.getUsername().length() < 1 || user.getUsername().length() > 12 || user.getUsername() == null) {
            return Result.error("用户名长度为1~12位");
        }
        if (user.getPassword().length() < 6 || user.getPassword().length() > 32 || user.getPassword() == null) {
            return Result.error("密码长度为6~32位");
        }
        if (user.getId().length() < 1 || user.getId().length() > 16 || user.getId() == null) {
            return Result.error("学号长度为1~16位");
        }
        //注册
        try {
            userMapper.addUser(user);
        } catch (Exception e) {
            e.printStackTrace();
            if (userMapper.getByUsername(user) != null) {
                return Result.error("用户名已被使用");
            }
            if (userMapper.getById(user) != null) {
                return Result.error("该学号或工号已被注册");
            }
            return Result.error("请联系管理员");
        }
        log.info(user.getUsername() + "注册了");
        Student student = new Student();
        student.setId(user.getId());
        //fake
        student.setSubject(generateFakeData(subjects));
        student.setClassName(generateFakeData(classes));
        student.setTutor(generateFakeData(teachernames));
        student.setRealName(generateFakeData(studentnames));
        //fake
        studentMapper.insert(student);
        return Result.success("注册成功!");
    }

    //fake
    private static String generateFakeData(String[] names) {
        Random random = new Random();
        return names[random.nextInt(names.length)];
    }

    private String[] subjects = {
            "计算机科学与技术",
            "软件工程",
            "电子信息工程",
            "通信工程",
            "数据科学与大数据技术",
            "物联网工程",
            "机械工程",
            "自动化",
            "电气工程及其自动化",
            "新能源科学与工程",
            "能源与动力工程",
            "航空航天科学与技术",
            "材料科学与工程",
            "生物医学工程",
            "环境科学与工程",
            "化学工程与工艺",
            "食品科学与工程",
            "土木工程",
            "建筑学",
            "风景园林"
    };

    private String[] classes = { "一班",
            "二班"};

    private String[] studentnames = {
            "张三",
            "李四",
            "王五",
            "赵六",
            "孙七",
            "周八",
            "刘九",
            "吴十",
            "黄一",
            "马二",
            "朱三",
            "陈四",
            "胡五",
            "林六",
            "郭七",
            "魏八",
            "梁九",
            "宋十",
            "雷一",
            "方二"
    };

    private String[] teachernames = {
            "张小明",
            "李红",
            "王大伟",
            "赵晓丽",
            "孙阳",
            "周美丽",
            "刘刚",
            "吴静",
            "黄健",
            "马磊",
            "朱洁",
            "陈明阳",
            "胡宇航",
            "林青",
            "郭军",
            "魏小丽",
            "梁志华",
            "宋婷婷",
            "雷阳",
            "方佳琪"
    };

}
